<script setup lang="ts">
import { ModalUtil } from '/@lib/utils/modal.ts'
import { sys_normal_disable, sys_user_sex } from '/@/const/Options.ts'
import { useModalStatus } from '/@lib/hooks/useModalStatus.ts'
import { useLoading } from '/@lib/hooks/useLoading.ts'
import { useForm } from '/@lib/hooks/useForm.ts'
import { usePagination } from '/@lib/hooks/usePagination.ts'
import { UserVO } from '/@/api/system/sysUser/types'
import { ApiSysUser } from '/@/api/system/sysUser'
import { ApiSysDept } from '/@/api/system/sysDept'
import { ApiSysPost } from '/@/api/system/sysPost'
import { ApiSysRole } from '/@/api/system/sysRole'

const { modalVisible, modalTitle, showModal, hideModal, setModalTitle } = useModalStatus()
const { loading, showLoading, hideLoading } = useLoading()
const formRef = ref()
const { form, resetForm } = useForm({
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: undefined,
  password: '123456',
  phoneNumber: undefined,
  email: undefined,
  sex: undefined,
  status: '0',
  remark: '',
  postIds: [],
  roleIds: []
})
const formRules = {
  deptId: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  userName: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
  password: [
    { required: true, message: '用户密码不能为空', trigger: 'blur' },
    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
    { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\ |', trigger: 'blur' }
  ],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
  phoneNumber: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  roleIds: [{ required: true, message: '用户角色不能为空', trigger: 'change' }]
}
const closeCancel = () => {
  formRef.value?.resetFields()
  resetForm()
  hideModal()
}

const deptTreeOptions = ref([])
const postOptions = ref([])
const roleOptions = ref([])
// const deptId = ref()

/** 打开 Modal 操作 */
const openAdd = async (_deptId?: any) => {
  showModal()
  setModalTitle('添加用户')
  form.deptId = _deptId
  // deptId.value = _deptId
  await handleOpenDefaultData()
}
const openEdit = async (row: any) => {
  showModal()
  setModalTitle('修改用户')
  // deptId.value = row.deptId
  form.deptId = row.deptId
  await handleOpenDefaultData(row)
}
defineExpose({ openAdd, openEdit })
const emit = defineEmits(['submit-success'])
/** 提交按钮 */
const submitForm = async () => {
  try {
    await formRef.value?.validate()
    showLoading()
    if (form.userId) {
      await ApiSysUser.update(form)
    } else {
      await ApiSysUser.save(form)
    }
    ModalUtil.msgSuccess('操作成功')
    hideModal()
    emit('submit-success')
  } finally {
    hideLoading()
  }
}
/** Modal Open 处理默认数据 */
const handleOpenDefaultData = async (row?: UserVO) => {
  showLoading()
  try {
    if (row) {
      // 修改用户
      const res = await ApiSysUser.getInfo(row.userId)
      Object.assign(form, res)
    }
    deptTreeOptions.value = await ApiSysDept.tree()
    postOptions.value = await ApiSysPost.listOptionSelect(form.deptId)
    await getTableList()
  } finally {
    hideLoading()
  }
}

const { loading: postLoading, showLoading: showPostLoading, hideLoading: hidePostLoading } = useLoading()
/** 部门树选中事件 切换岗位列表 */
const handleDeptChange = async (deptId: number | string) => {
  showPostLoading()
  try {
    postOptions.value = ApiSysPost.listOptionSelect(deptId)
    form.postIds = []
  } finally {
    hidePostLoading()
  }
}

const {
  pageNum, pageSize, total, setTotal, onChangeCurrent
} = usePagination(() => getTableList())
const { form: queryParams } = useForm({
  pageNum: computed(() => pageNum.value),
  pageSize: computed(() => pageSize.value)
})
const vipSelectTableRef = ref()
const { loading: roleLoading, showLoading: showRoleLoading, hideLoading: hideRoleLoading } = useLoading()
const getTableList = async () => {
  showRoleLoading()
  try {
    const res = await ApiSysRole.pageOptionSelect(queryParams)
    roleOptions.value = res.rows
    setTotal(res.total)
    await vipSelectTableRef.value.setDefaultSelection()
  } finally {
    hideRoleLoading()
  }
}
const handleSelectTableChange = (value: any) => {
}

const formItems = ref([
  {
    prop: 'deptId',
    label: '归属部门',
    slot: 'slot-deptId',
    span: 2
  },
  {
    prop: 'userName',
    label: '登录账号',
    attrs: {
      placeholder: '请输入登录账号'
    }
  },
  {
    prop: 'password',
    label: '用户密码',
    attrs: {
      placeholder: '请输入用户密码',
      type: 'password',
      maxlength: 20,
      showPassword: true
    }
  },
  {
    prop: 'nickName',
    label: '用户昵称',
    attrs: {
      placeholder: '请输入用户昵称'
    }
  },
  {
    prop: 'sex',
    label: '用户性别',
    slot: 'agel-select',
    attrs: {
      placeholder: '请选择用户性别',
      options: sys_user_sex
    }
  },
  {
    prop: 'phoneNumber',
    label: '手机号码',
    attrs: {
      placeholder: '请输入手机号码'
    }
  },
  {
    prop: 'email',
    label: '邮箱',
    attrs: {
      placeholder: '请输入邮箱'
    }
  },
  {
    prop: 'postIds',
    label: '岗位',
    slot: 'agel-select',
    attrs: {
      placeholder: '请选择岗位',
      loading: postLoading,
      options: postOptions,
      multiple: true
    },
    span: 2
  },
  {
    prop: 'roleIds',
    label: '角色',
    slot: 'slot-roleIds',
    span: 2,
    inlineMessage: true
  },
  {
    prop: 'status',
    label: '状态',
    slot: 'agel-radio',
    attrs: {
      border: true,
      options: sys_normal_disable
    },
    span: 2
  },
  {
    prop: 'remark',
    label: '备注',
    attrs: {
      placeholder: '请输入内容',
      type: 'textarea',
      rows: 2,
      showWordLimit: true,
      maxlength: 200
    }
  }
])
</script>

<template>
  <!-- 添加或修改对话框 -->
  <el-dialog
    :title="modalTitle"
    v-model="modalVisible"
    width="50%"
    top="10vh"
    @close="closeCancel"
    append-to-body
    destroy-on-close
    :close-on-click-modal="false"
  >
    <ElForm
      ref="formRef"
      v-loading="loading"
      :model="form"
      :rules="formRules"
      label-width="140px"
      label-position="right"
    >
      <AgelFormDesc :items="formItems" border :column="2">
        <!--        <template #slot-select>-->
        <!--          <el-select v-model="form.sex" placeholder="请选择用户性别">-->
        <!--            <el-option v-for="item in sys_user_sex" :key="item.value" :label="item.label" :value="item.value" />-->
        <!--          </el-select>-->
        <!--        </template>-->
        <template #slot-deptId>
          <el-tree-select
            v-model="form.deptId"
            :data="deptTreeOptions"
            value-key="id"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            placeholder="请选择归属部门"
            check-strictly
            default-expand-all
            @change="handleDeptChange"
          />
        </template>

        <template #slot-roleIds>
          <VipSelectTable
            ref="vipSelectTableRef"
            v-model="form.roleIds"
            :props="{ label: 'roleName', value: 'roleId' }"
            :multiple="true"
            placeholder="请选择角色"
            clearable
            pagination
            :loading="roleLoading"
            :table-data="roleOptions"
            :total="total"
            :page-size="pageSize"
            :current-page="pageNum"
            @page-change="onChangeCurrent"
            @change="handleSelectTableChange"
          >
            <!--            <el-table-column align="center" label="角色名称" prop="label" show-overflow-tooltip />-->
            <!--            <el-table-column align="center" label="权限字符" prop="value" show-overflow-tooltip />-->
            <el-table-column align="center" label="角色名称" prop="roleName" show-overflow-tooltip />
            <el-table-column align="center" label="权限字符" prop="roleKey" show-overflow-tooltip />
          </VipSelectTable>
        </template>
      </AgelFormDesc>
    </ElForm>

    <!-- 底部按钮 -->
    <template #footer>
      <div>
        <el-button @click="closeCancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
